package com.school.graduation.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.school.graduation.R;
import com.school.graduation.bean.SignCallBack;
import com.school.graduation.common.base.BaseActivity;
import com.school.graduation.internet.SignInterface;
import com.school.graduation.model.Student;
import com.school.graduation.ui.activity.mainUi.MainActivity;
import com.school.graduation.util.LogUtil;
import com.school.graduation.util.ToastUtil;
import com.school.graduation.util.UserUtil;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class SignInActivity extends BaseActivity{
    public static final int GET_SIGN_UP_DATA = 100;
    public static final int SIGN_IN_SUCCESS = 2;

    @Bind(R.id.sign_name)
    EditText signName;
    @Bind(R.id.sign_password)
    EditText signPassword;
    @Bind(R.id.sign_button)
    TextView signButton;
    @Bind(R.id.sign_up)
    TextView signUp;
    @Bind(R.id.sign_in_layout)
    RelativeLayout signInLayout;
    private boolean signIn = true;
    private boolean inputEmpty = false;
    private SharedPreferences.Editor editor;

    @Override
    public void onResume() {
        super.onResume();
        signIn = true;
    }


    @Override
    public int getContentView() {
        return R.layout.activity_sign_in;
    }

    @Override
    public void initData() {
        keepBtAndSignUpNotOver();
        setEditTouchListener();
        initSp();
    }

    private void initSp() {
    }

    private void setEditTouchListener() {
        signName.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (signPassword.getText().toString().equals("")) signPassword.setHint("Password");
                signName.setHint("");
                signName.setCursorVisible(true);
                return false;
            }
        });
        signPassword.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (signName.getText().toString().equals("")) signName.setHint("Name or Surname");
                signPassword.setHint("");
                signPassword.setCursorVisible(true);
                return false;
            }
        });
    }

    private void keepBtAndSignUpNotOver() {
        signInLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (!signIn) return;
                Rect rect = new Rect();
                signInLayout.getWindowVisibleDisplayFrame(rect);
                int layoutInvisibleHeight = signInLayout.getRootView().getHeight() - rect.bottom;
                if (layoutInvisibleHeight>=200){
                    int scrollHeight = layoutInvisibleHeight - (signInLayout.getMeasuredHeight()-signButton.getBottom());
                    if (scrollHeight>0) signInLayout.scrollTo(0,scrollHeight);
                }else signInLayout.scrollTo(0,0);
            }
        });
    }

    @OnClick({ R.id.sign_button, R.id.sign_up})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sign_button:
                signIn(signName.getText().toString(),signPassword.getText().toString());
                break;
            case R.id.sign_up:
                signIn = false;
                startActivityForResult(new Intent(SignInActivity.this,SignUpActivity.class),GET_SIGN_UP_DATA);
                break;
        }
    }

    private void signIn(String name, final String password) {
        checkInput(name);
        checkInput(password);
        if (!inputEmpty){
            final SharedPreferences sp = getApplicationContext().getSharedPreferences("user_cache", Context.MODE_MULTI_PROCESS |
                    Activity.MODE_WORLD_WRITEABLE);
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://123.206.20.29:3000/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            SignInterface sign = retrofit.create(SignInterface.class);
            Call<SignCallBack> call = sign.signIn(name,password);
            call.enqueue(new Callback<SignCallBack>() {
                @Override
                public void onResponse(Call<SignCallBack> call, Response<SignCallBack> response) {
                    if (response.isSuccessful()){
                        SignCallBack callBack = response.body();
                        editor = sp.edit();
                        editor.putString("password",password);
                        editor.commit();
                        editor.apply();
                        signIn(callBack);
                    }else ToastUtil.makeShortToast(context,response.errorBody().toString());
                }

                @Override
                public void onFailure(Call<SignCallBack> call, Throwable t) {
                    ToastUtil.makeShortToast(context,t.toString());
                }
            });
        }
    }

    private void signIn(SignCallBack callBack) {
        int user = callBack.getUser();
        if (user==SIGN_IN_SUCCESS){
            SharedPreferences sp = getApplicationContext().getSharedPreferences("user_cache", Context.MODE_MULTI_PROCESS |
                    Activity.MODE_WORLD_WRITEABLE);
            editor = sp.edit();
            editor.putString("name",callBack.getData().getName());
            editor.putString("id",callBack.getData().get_id());
            editor.putString("city",callBack.getData().getCity());
            LogUtil.d("sign",callBack.getData().getName());
            UserUtil.hasLogIn = true;
            editor.apply();
            editor.commit();
            ToastUtil.makeShortToast(context,callBack.getStatus());
            startActivity(new Intent(context,MainActivity.class));
            finish();
        }else {
            ToastUtil.makeShortToast(context,callBack.getStatus());
        }
    }

    private void checkInput(String input) {
        if ("".equals(input)) {
            ToastUtil.makeShortToast(context,"注册信息不能为空");
            inputEmpty = true;
            return;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK&&requestCode==GET_SIGN_UP_DATA){
            String name = data.getStringExtra("name");
            String password = data.getStringExtra("password");
            signName.setText(name);
            signPassword.setText(password);
            signIn(name,password);
        }
    }
}
